package org.nci.platform.workflow.controller;

import com.alibaba.fastjson2.JSONObject;
import gh.priv.general.common.vo.PageResult;
import gh.priv.general.common.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.UserTask;
import org.nci.platform.workflow.dto.FlowNextDto;
import org.nci.platform.workflow.dto.FlowTaskDto;
import org.nci.platform.workflow.dto.FlowViewerDto;
import org.nci.platform.workflow.service.IFlowTaskService;
import org.nci.platform.workflow.vo.FlowQueryVo;
import org.nci.platform.workflow.vo.FlowRecordVo;
import org.nci.platform.workflow.vo.FlowTaskVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>工作流任务管理<p>
 *
 * @author Tony
 * @date 2021-04-03
 */
@Slf4j
@Tag(name = "工作流流程任务管理")
@RestController
@RequestMapping("/flowable/task")
public class FlowTaskController {

    @Resource
    private IFlowTaskService flowTaskService;

    @Operation(summary = "我发起的流程")
    @GetMapping(value = "/myProcess")
    public Result<PageResult<FlowTaskVo>> myProcess(FlowQueryVo queryVo) {
        return Result.success(flowTaskService.myProcess(queryVo));
    }

    @Operation(summary = "取消申请")
    @PostMapping(value = "/stopProcess")
    public Result<Boolean> stopProcess(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.stopProcess(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "撤回流程")
    @PostMapping(value = "/revokeProcess")
    public Result<Boolean> revokeProcess(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.revokeProcess(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "获取待办列表")
    @GetMapping(value = "/todoList")
    public Result<PageResult<FlowTaskVo>> todoList(FlowQueryVo queryVo) {
        return Result.success(flowTaskService.todoList(queryVo));
    }

    @Operation(summary = "获取已办任务")
    @GetMapping(value = "/finishedList")
    public Result<PageResult<FlowTaskVo>> finishedList(FlowQueryVo queryVo) {
        return Result.success(flowTaskService.finishedList(queryVo));
    }


    @Operation(summary = "流程历史流转记录")
    @GetMapping(value = "/flowRecord")
    public Result<FlowRecordVo> flowRecord(String procInsId, String deployId) {
        return Result.success(flowTaskService.flowRecord(procInsId, deployId));
    }

    @Operation(summary = "根据任务ID查询挂载的表单信息")
    @GetMapping(value = "/getTaskForm")
    public Result<String> getTaskForm(String taskId) {
        return Result.success(flowTaskService.getTaskForm(taskId));
    }


    @Operation(summary = "流程初始化表单")
    @GetMapping(value = "/flowFormData")
    public Result<JSONObject> flowFormData(@Valid @NotBlank String deployId) {
        return Result.success(flowTaskService.flowFormData(deployId));
    }

    @Operation(summary = "获取流程变量")
    @GetMapping(value = "/processVariables/{taskId}")
    public Result<Map<String,Object>> processVariables(@Parameter(description = "流程任务Id") @PathVariable(value = "taskId") String taskId) {
        return Result.success(flowTaskService.processVariables(taskId));
    }

    @Operation(summary = "审批任务")
    @PostMapping(value = "/complete")
    public Result<Boolean> complete(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.complete(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "驳回任务")
    @PostMapping(value = "/reject")
    public Result<Boolean> taskReject(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.taskReject(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "退回任务")
    @PostMapping(value = "/return")
    public Result<Boolean> taskReturn(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.taskReturn(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "获取所有可回退的节点")
    @PostMapping(value = "/returnList")
    public Result<List<UserTask>> findReturnTaskList(@RequestBody FlowTaskDto flowTaskDto) {
        return Result.success(flowTaskService.findReturnTaskList(flowTaskDto));
    }

    @Operation(summary = "删除任务")
    @DeleteMapping(value = "/delete")
    public Result<Boolean> delete(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.deleteTask(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "认领/签收任务")
    @PostMapping(value = "/claim")
    public Result<Boolean> claim(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.claim(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "取消认领/签收任务")
    @PostMapping(value = "/unClaim")
    public Result<Boolean> unClaim(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.unClaim(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "委派任务")
    @PostMapping(value = "/delegateTask")
    public Result<Boolean> delegate(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.delegateTask(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "任务归还")
    @PostMapping(value = "/resolveTask")
    public Result<Boolean> resolveTask(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.resolveTask(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "转办任务")
    @PostMapping(value = "/assignTask")
    public Result<Boolean> assign(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.assignTask(flowTaskDto);
        return Result.success();
    }

    @PostMapping(value = "/addMultiInstanceExecution")
    @Operation(summary = "多实例加签")
    public Result<Boolean> addMultiInstanceExecution(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.addMultiInstanceExecution(flowTaskDto);
        return Result.success();
    }

    @PostMapping(value = "/deleteMultiInstanceExecution")
    @Operation(summary = "多实例减签")
    public Result<Boolean> deleteMultiInstanceExecution(@RequestBody FlowTaskDto flowTaskDto) {
        flowTaskService.deleteMultiInstanceExecution(flowTaskDto);
        return Result.success();
    }

    @Operation(summary = "获取下一节点")
    @PostMapping(value = "/nextFlowNode")
    public Result<FlowNextDto> getNextFlowNode(@RequestBody FlowTaskDto flowTaskDto) {
        return Result.success(flowTaskService.getNextFlowNode(flowTaskDto));
    }

    @Operation(summary = "流程发起时获取下一节点")
    @PostMapping(value = "/nextFlowNodeByStart")
    public Result<FlowNextDto> getNextFlowNodeByStart(@RequestBody FlowTaskDto flowTaskDto) {
        return Result.success(flowTaskService.getNextFlowNodeByStart(flowTaskDto));
    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @Operation(summary = "生成流程图")
    @GetMapping("/diagram/{processId}")
    public void genProcessDiagram(HttpServletResponse response,
                                  @PathVariable("processId") String processId) {
        InputStream inputStream = flowTaskService.diagram(processId);
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(inputStream);
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取流程执行节点
     *
     * @param procInsId 流程实例编号
     * @param procInsId 任务执行编号
     */
    @Operation(summary = "获取流程执行节点")
    @GetMapping("/flowViewer/{procInsId}/{executionId}")
    public Result<List<FlowViewerDto>> getFlowViewer(@PathVariable("procInsId") String procInsId,
                                                     @PathVariable("executionId") String executionId) {
        return Result.success(flowTaskService.getFlowViewer(procInsId, executionId));
    }

    /**
     * 流程节点信息
     *
     * @param procInsId 流程实例id
     * @return
     */
    @Operation(summary = "流程节点信息实例ID查询")
    @GetMapping("/flowXmlAndNode")
    public Result<Map<String, Object>> flowXmlAndNode(@RequestParam(value = "procInsId", required = false) String procInsId,
                                 @RequestParam(value = "deployId", required = false) String deployId) {
        return Result.success(flowTaskService.flowXmlAndNode(procInsId, deployId));
    }

    /**
     * 流程节点表单
     *
     * @param taskId 流程任务编号
     * @return
     */
    @Operation(summary = "流程节点表单")
    @GetMapping("/flowTaskForm")
    public Result<Map<String, Object>> flowTaskForm(@RequestParam(value = "taskId", required = false) String taskId) throws Exception {
        return Result.success(flowTaskService.flowTaskForm(taskId));
    }


    /**
     * 流程节点信息
     *
     * @param procInsId 流程实例编号
     * @param elementId 流程节点编号
     * @return
     */
    @Operation(summary = "流程节点信息")
    @GetMapping("/flowTaskInfo")
    public Result<FlowTaskVo> flowTaskInfo(@RequestParam(value = "procInsId") String procInsId,
                               @RequestParam(value = "elementId") String elementId) {
        return Result.success(flowTaskService.flowTaskInfo(procInsId, elementId));
    }

}
